<template>
  <div class="elderly-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>老人基本信息</h2>
           <el-button 
            type="primary" 
            size="small"
            @click="openEditDialog"
            :disabled="!elderly"
          >
            编辑信息
          </el-button>
        </div>
      </template>
      <div v-if="elderly" class="profile-content">
        <el-descriptions :column="3" border size="large">
          <el-descriptions-item label="姓名" label-class-name="label-bold">
            <span class="value-text">{{ elderly.name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="年龄" label-class-name="label-bold">
            <span class="value-text">{{ elderly.age }}岁</span>
          </el-descriptions-item>
          <el-descriptions-item label="性别" label-class-name="label-bold">
            <span class="value-text">{{ elderly.sex }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话" label-class-name="label-bold">
            <span class="value-text">{{ elderly.phone }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="身高" label-class-name="label-bold">
            <span class="value-text">{{ elderly.height }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="体重" label-class-name="label-bold">
            <span class="value-text">{{ elderly.weight }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="血型" label-class-name="label-bold">
            <span class="value-text">{{ elderly.bloodType }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="地址" :span="3" label-class-name="label-bold">
            <span class="value-text">{{ elderly.address }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="紧急联系人" label-class-name="label-bold">
            <span class="value-text">{{ elderly.emergencyContact.name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系人电话" label-class-name="label-bold">
            <span class="value-text">{{ elderly.emergencyContact.phone }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="关系" label-class-name="label-bold">
            <span class="value-text">{{ elderly.emergencyContact.relationship }}</span>
          </el-descriptions-item>
          <!-- <el-descriptions-item label="病史" :span="3" label-class-name="label-bold">
            <div class="tags-container">
              <el-tag v-for="(history, i) in elderly.medicalHistory" :key="i" type="warning" size="large">
                {{ history }}
              </el-tag>
              <span v-if="elderly.medicalHistory.length === 0" class="no-data">无</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="过敏史" :span="3" label-class-name="label-bold">
            <div class="tags-container">
              <el-tag v-for="(allergy, i) in elderly.allergies" :key="i" type="danger" size="large">
                {{ allergy }}
              </el-tag>
              <span v-if="elderly.allergies.length === 0" class="no-data">无</span>
            </div>
          </el-descriptions-item> -->
        </el-descriptions>
      </div>
      <div v-else class="no-data-container">
        <el-empty description="暂无绑定老人信息" :image-size="200">
          <el-button type="primary" @click="openBindDialog">绑定老人信息</el-button>
        </el-empty>
      </div>
    </el-card>
      <el-dialog
      v-model="showBindDialog"
      title="绑定老人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="bindForm" label-width="100px">
        <el-form-item label="老人电话">
          <el-input
            v-model="bindForm.phone"
            placeholder="请输入老人的联系电话"
            clearable
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showBindDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmBind"
          :loading="loading"
          :disabled="!bindForm.phone"
        >
          确认绑定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showEditDialog"
      title="编辑老人信息"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="editForm" 
        label-width="120px"
        ref="editFormRef"
        :rules="editRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="editForm.sex" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="editForm.age" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="editForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血型" prop="bloodType">
              <el-select v-model="editForm.bloodType" style="width: 100%">
                <el-option label="A" value="A" />
                <el-option label="B" value="B" />
                <el-option label="AB" value="AB" />
                <el-option label="O" value="O" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身高" prop="height">
              <el-input v-model="editForm.height" placeholder="例如: 170cm" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="体重" prop="weight">
          <el-input v-model="editForm.weight" placeholder="例如: 65kg" />
        </el-form-item>

        <el-divider>紧急联系人信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="emergencyContact.name">
              <el-input v-model="editForm.emergencyContact.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="emergencyContact.phone">
              <el-input v-model="editForm.emergencyContact.phone" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="关系" prop="emergencyContact.relationship">
          <el-input v-model="editForm.emergencyContact.relationship" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitEditForm"
          :loading="editLoading"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, reactive } from 'vue'
import { useElderlyStore } from '@/stores/elderly'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { 
  getElderlyByPhone, 
  bindElderlyToUser,
  getElderlyById,
  updateElderly 
} from '@/api/elderlyInfo/elderlyInfo'
import { onMounted } from 'vue'
import { User } from '@element-plus/icons-vue'
import { getUserById } from '@/api/userInfo/userInfo'
interface UserInfo {
  id: string;
  username: string;
  realname: string | undefined;
  phone: string | undefined;
  email: string | undefined;
  elderlyId: string | undefined;
}

interface EmergencyContact {
  name: string;
  phone: string;
  relationship: string;
}

interface ElderlyInfo {
  id: string;
  name: string;
  sex: string;
  age: string;
  phone: string;
  address: string;
  bloodType: string;
  height: string;
  weight: string;
  emergencyContact: EmergencyContact;
}
const user = ref<UserInfo | null>(null);
const userString = localStorage.getItem('user')
const elderly = ref<ElderlyInfo | null>(null)
const showBindDialog = ref(false)
const loading = ref(false)
const bindForm = ref({
  phone: ''
})
const showEditDialog = ref(false)
const editLoading = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive<ElderlyInfo>({
  id: '',
  name: '',
  sex: '',
  age: '',
  phone: '',
  address: '',
  bloodType: '',
  height: '',
  weight: '',
  emergencyContact: {
    name: '',
    phone: '',
    relationship: ''
  }
})

const editRules: FormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  'emergencyContact.name': [{ required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }],
  'emergencyContact.phone': [{ required: true, message: '请输入紧急联系人电话', trigger: 'blur' }],
  'emergencyContact.relationship': [{ required: true, message: '请输入与紧急联系人的关系', trigger: 'blur' }]
}

// 打开编辑对话框
const openEditDialog = () => {
  if (!elderly.value) return
  
  // 将当前老人信息复制到编辑表单
  Object.assign(editForm, elderly.value)
  showEditDialog.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    const { id, ...updateData } = editForm
    const response = await updateElderly(id, updateData)
    
    if (response.code === 200) {
      ElMessage.success('保存成功')
      showEditDialog.value = false
      // 更新本地数据
      elderly.value = { ...editForm }
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请检查表单')
  } finally {
    editLoading.value = false
  }
}

//载入页面时根据userId获取当前用户绑定的老人信息
onMounted(async ()  => {
  console.log(userString)
  if (userString) {
    user.value = JSON.parse(userString) as UserInfo;
    const response = await getUserById(user.value.id)
    user.value = response.data
    localStorage.setItem('user', JSON.stringify(user.value))
    console.log(user.value?.elderlyId)
    getElderlyById(user.value?.elderlyId??'').then((response) => {
    elderly.value = response.data
    })
    localStorage.setItem('elderlyId', user.value?.elderlyId??'')
  }
  else {
    ElMessage.warning('请先绑定老人信息')
  }
  }
)
// 打开绑定对话框
const openBindDialog = () => {
  showBindDialog.value = true
  bindForm.value.phone = ''
}

// 确认绑定
const confirmBind = async () => {
  if (!bindForm.value.phone) {
    ElMessage.warning('请输入老人电话')
    return
  }

  loading.value = true
  try {
    // 1. 根据手机号查询老人信息
    const response = await getElderlyByPhone(bindForm.value.phone)
    if (response.code !== 200 || !response.data || response.data.length === 0) {
      ElMessage.warning('未找到该电话对应的老人信息')
      return
    }
    console.log(response.data)
    const elderlyData = response.data // 假设返回的是数组，取第一个
    elderly.value = elderlyData
    console.log('elderlyData:', elderlyData)
    // 2. 绑定老人到当前用户
    const bindResponse = await bindElderlyToUser(
      user.value?.id??'',
      elderlyData.id
    )
    
    if (bindResponse.code === 200) {
      ElMessage.success('绑定成功')
      showBindDialog.value = false
    } else {
      ElMessage.error(bindResponse.message || '绑定失败')
    }
  } catch (error) {
    console.error('绑定失败:', error)
    ElMessage.error('绑定失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.elderly-profile {
  height: 100%;
  width: 100%;
}

.profile-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.profile-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.profile-content {
  padding: 24px;
  height: 100%;
  overflow-y: auto;
}

.no-data-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tags-container .el-tag {
  margin: 0;
}

.no-data {
  color: #999;
  font-style: italic;
}

/* 自定义描述列表样式 */
:deep(.label-bold) {
  font-weight: 600 !important;
  color: #333 !important;
  background-color: #fafafa !important;
}

:deep(.value-text) {
  font-size: 14px;
  color: #333;
}
.el-form-item {
  margin-bottom: 18px;
}

.el-divider {
  margin: 20px 0;
}
/* 响应式设计 */
@media (max-width: 1200px) {
  .profile-content {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .profile-content {
    padding: 16px;
  }
  
  .card-header h2 {
    font-size: 18px;
  }
}
</style>